<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>🧠 ERNIE-4.5 + 智源研究院 - 超级个体生产力工具</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', 'PingFang SC', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            text-align: center;
            margin-bottom: 30px;
            color: white;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
        }

        .header .subtitle {
            font-size: 1.2em;
            opacity: 0.9;
            margin-bottom: 20px;
        }

        .tech-badges {
            display: flex;
            justify-content: center;
            gap: 15px;
            flex-wrap: wrap;
            margin-bottom: 30px;
        }

        .badge {
            background: rgba(255,255,255,0.2);
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 0.9em;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255,255,255,0.3);
        }

        .main-content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
            margin-bottom: 30px;
        }

        .card {
            background: rgba(255,255,255,0.95);
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255,255,255,0.2);
        }

        .card h2 {
            color: #667eea;
            margin-bottom: 20px;
            font-size: 1.5em;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .task-selector {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
            gap: 10px;
            margin-bottom: 20px;
        }

        .task-btn {
            padding: 12px 16px;
            border: 2px solid #667eea;
            background: white;
            color: #667eea;
            border-radius: 10px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 0.9em;
            text-align: center;
        }

        .task-btn:hover, .task-btn.active {
            background: #667eea;
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102,126,234,0.3);
        }

        .input-group {
            margin-bottom: 20px;
        }

        .input-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #555;
        }

        .input-group textarea {
            width: 100%;
            padding: 15px;
            border: 2px solid #e1e5e9;
            border-radius: 10px;
            font-size: 16px;
            resize: vertical;
            min-height: 120px;
            transition: border-color 0.3s ease;
        }

        .input-group textarea:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102,126,234,0.1);
        }

        .send-btn {
            width: 100%;
            padding: 15px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .send-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(102,126,234,0.3);
        }

        .send-btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .chat-area {
            height: 400px;
            overflow-y: auto;
            border: 2px solid #e1e5e9;
            border-radius: 10px;
            padding: 20px;
            background: #f8f9fa;
        }

        .message {
            margin-bottom: 20px;
            padding: 15px;
            border-radius: 10px;
            animation: fadeIn 0.5s ease;
        }

        .message.user {
            background: #667eea;
            color: white;
            margin-left: 20%;
        }

        .message.assistant {
            background: white;
            border: 2px solid #e1e5e9;
            margin-right: 20%;
        }

        .message .meta {
            font-size: 0.8em;
            opacity: 0.7;
            margin-bottom: 8px;
        }

        .knowledge-sources {
            margin-top: 15px;
            padding: 15px;
            background: rgba(102,126,234,0.1);
            border-radius: 8px;
            border-left: 4px solid #667eea;
        }

        .knowledge-item {
            margin-bottom: 10px;
            padding: 10px;
            background: white;
            border-radius: 6px;
            font-size: 0.9em;
        }

        .knowledge-item .topic {
            font-weight: 600;
            color: #667eea;
            margin-bottom: 5px;
        }

        .knowledge-item .source {
            font-size: 0.8em;
            color: #666;
            margin-top: 5px;
        }

        .status-panel {
            background: rgba(255,255,255,0.95);
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
        }

        .status-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 0;
            border-bottom: 1px solid #e1e5e9;
        }

        .status-item:last-child {
            border-bottom: none;
        }

        .status-indicator {
            padding: 4px 12px;
            border-radius: 15px;
            font-size: 0.8em;
            font-weight: 600;
        }

        .status-indicator.success {
            background: #d4edda;
            color: #155724;
        }

        .status-indicator.warning {
            background: #fff3cd;
            color: #856404;
        }

        .status-indicator.error {
            background: #f8d7da;
            color: #721c24;
        }

        .loading {
            display: none;
            text-align: center;
            padding: 20px;
        }

        .spinner {
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 10px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .features-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-top: 30px;
        }

        .feature-card {
            background: rgba(255,255,255,0.9);
            padding: 20px;
            border-radius: 15px;
            text-align: center;
            transition: transform 0.3s ease;
        }

        .feature-card:hover {
            transform: translateY(-5px);
        }

        .feature-icon {
            font-size: 2em;
            margin-bottom: 10px;
        }

        @media (max-width: 768px) {
            .main-content {
                grid-template-columns: 1fr;
            }
            
            .header h1 {
                font-size: 2em;
            }
            
            .task-selector {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🧠 ERNIE-4.5 + 智源研究院</h1>
            <div class="subtitle">超级个体生产力工具 · 沉浸式互动学习伴侣</div>
            <div class="tech-badges">
                <div class="badge">🤖 ERNIE-4.5-0.3B-Paddle</div>
                <div class="badge">🎓 智源研究院数据</div>
                <div class="badge">🚀 多模态感知</div>
                <div class="badge">🧩 深度认知融合</div>
            </div>
        </div>

        <!-- 系统状态面板 -->
        <div class="status-panel">
            <h3 style="margin-bottom: 15px; color: #667eea;">🔧 系统状态</h3>
            <div id="systemStatus">
                <div class="status-item">
                    <span>ERNIE模型状态</span>
                    <span class="status-indicator" id="ernieStatus">检查中...</span>
                </div>
                <div class="status-item">
                    <span>PaddlePaddle框架</span>
                    <span class="status-indicator" id="paddleStatus">检查中...</span>
                </div>
                <div class="status-item">
                    <span>智源知识库</span>
                    <span class="status-indicator" id="zhiyuanStatus">检查中...</span>
                </div>
                <div class="status-item">
                    <span>知识类别数量</span>
                    <span class="status-indicator" id="knowledgeCount">-</span>
                </div>
            </div>
        </div>

        <div class="main-content">
            <!-- 智能对话区域 -->
            <div class="card">
                <h2>💬 智能对话助手</h2>
                
                <div class="task-selector">
                    <button class="task-btn active" data-task="general">综合咨询</button>
                    <button class="task-btn" data-task="learning">学习指导</button>
                    <button class="task-btn" data-task="productivity">生产力</button>
                    <button class="task-btn" data-task="creativity">创意激发</button>
                    <button class="task-btn" data-task="analysis">深度分析</button>
                </div>

                <div class="input-group">
                    <label for="userInput">请输入您的问题或需求：</label>
                    <textarea id="userInput" placeholder="例如：如何提高学习效率？如何制定工作计划？如何激发创造力？"></textarea>
                </div>

                <button class="send-btn" id="sendBtn">🚀 发送消息</button>

                <div class="loading" id="loading">
                    <div class="spinner"></div>
                    <div>ERNIE模型正在思考中...</div>
                </div>
            </div>

            <!-- 对话历史区域 -->
            <div class="card">
                <h2>📝 对话历史</h2>
                <div class="chat-area" id="chatArea">
                    <div class="message assistant">
                        <div class="meta">系统消息 · 刚刚</div>
                        <div>欢迎使用基于ERNIE-4.5和智源研究院数据的超级个体生产力工具！我可以为您提供学习指导、工作建议、创意激发和深度分析等服务。请选择任务类型并输入您的问题。</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 功能特色展示 -->
        <div class="features-grid">
            <div class="feature-card">
                <div class="feature-icon">🧠</div>
                <h3>ERNIE-4.5模型</h3>
                <p>基于百度文心大模型4.5系列，具备强大的语言理解和生成能力</p>
            </div>
            <div class="feature-card">
                <div class="feature-icon">🎓</div>
                <h3>智源研究院数据</h3>
                <p>融合科研级知识库，提供专业、权威的内容支持</p>
            </div>
            <div class="feature-card">
                <div class="feature-icon">🚀</div>
                <h3>超级个体工具</h3>
                <p>个性化生产力提升，助力成为更高效的超级个体</p>
            </div>
            <div class="feature-card">
                <div class="feature-icon">🎯</div>
                <h3>沉浸式学习</h3>
                <p>互动式学习体验，深度个性化的知识传递</p>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let currentTaskType = 'general';
        let isLoading = false;

        // DOM元素
        const userInput = document.getElementById('userInput');
        const sendBtn = document.getElementById('sendBtn');
        const chatArea = document.getElementById('chatArea');
        const loading = document.getElementById('loading');
        const taskBtns = document.querySelectorAll('.task-btn');

        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            checkSystemStatus();
            setupEventListeners();
        });

        // 设置事件监听器
        function setupEventListeners() {
            // 任务类型选择
            taskBtns.forEach(btn => {
                btn.addEventListener('click', function() {
                    taskBtns.forEach(b => b.classList.remove('active'));
                    this.classList.add('active');
                    currentTaskType = this.dataset.task;
                });
            });

            // 发送消息
            sendBtn.addEventListener('click', sendMessage);
            
            // 回车发送
            userInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    sendMessage();
                }
            });
        }

        // 检查系统状态
        async function checkSystemStatus() {
            try {
                const response = await fetch('/api/model_status');
                const data = await response.json();
                
                // 更新状态显示
                updateStatus('ernieStatus', data.ernie_loaded, 'ERNIE模型已加载', 'ERNIE模拟模式');
                updateStatus('paddleStatus', data.paddle_available, 'PaddlePaddle可用', 'PaddlePaddle未安装');
                updateStatus('zhiyuanStatus', true, '智源知识库已加载', '智源知识库错误');
                
                document.getElementById('knowledgeCount').textContent = data.zhiyuan_knowledge_categories?.length || 0;
                document.getElementById('knowledgeCount').className = 'status-indicator success';
                
            } catch (error) {
                console.error('状态检查失败:', error);
                updateStatus('ernieStatus', false, '', '连接失败');
                updateStatus('paddleStatus', false, '', '连接失败');
                updateStatus('zhiyuanStatus', false, '', '连接失败');
            }
        }

        // 更新状态指示器
        function updateStatus(elementId, isSuccess, successText, errorText) {
            const element = document.getElementById(elementId);
            if (isSuccess) {
                element.textContent = successText;
                element.className = 'status-indicator success';
            } else {
                element.textContent = errorText;
                element.className = 'status-indicator warning';
            }
        }

        // 发送消息
        async function sendMessage() {
            const message = userInput.value.trim();
            if (!message || isLoading) return;

            // 显示用户消息
            addMessage('user', message);
            
            // 清空输入框
            userInput.value = '';
            
            // 显示加载状态
            setLoading(true);

            try {
                const response = await fetch('/api/chat', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        message: message,
                        task_type: currentTaskType
                    })
                });

                const data = await response.json();

                if (data.success) {
                    // 显示AI回复
                    addMessage('assistant', data.response, data.knowledge_sources, data.metadata);
                } else {
                    addMessage('assistant', `错误: ${data.error}`, null, null, true);
                }

            } catch (error) {
                console.error('发送消息失败:', error);
                addMessage('assistant', '抱歉，服务暂时不可用，请稍后重试。', null, null, true);
            } finally {
                setLoading(false);
            }
        }

        // 添加消息到聊天区域
        function addMessage(type, content, knowledgeSources = null, metadata = null, isError = false) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${type}`;
            
            const now = new Date().toLocaleTimeString();
            let messageHTML = `<div class="meta">${type === 'user' ? '您' : 'AI助手'} · ${now}</div>`;
            
            if (isError) {
                messageHTML += `<div style="color: #dc3545;">${content}</div>`;
            } else {
                messageHTML += `<div>${content}</div>`;
            }

            // 添加知识来源
            if (knowledgeSources && knowledgeSources.length > 0) {
                messageHTML += '<div class="knowledge-sources">';
                messageHTML += '<div style="font-weight: 600; margin-bottom: 10px;">📚 智源研究院知识来源：</div>';
                
                knowledgeSources.forEach(source => {
                    messageHTML += `
                        <div class="knowledge-item">
                            <div class="topic">${source.topic}</div>
                            <div>${source.content}</div>
                            <div class="source">来源：${source.source} (置信度: ${(source.confidence * 100).toFixed(1)}%)</div>
                        </div>
                    `;
                });
                
                messageHTML += '</div>';
            }

            // 添加元数据
            if (metadata) {
                messageHTML += `
                    <div style="margin-top: 10px; padding: 8px; background: rgba(0,0,0,0.05); border-radius: 5px; font-size: 0.8em;">
                        🤖 ${metadata.model} | 🎓 ${metadata.knowledge_base} | 
                        ⚡ ${metadata.generation_time.toFixed(2)}s | 
                        📊 置信度: ${(metadata.confidence * 100).toFixed(1)}%
                    </div>
                `;
            }

            messageDiv.innerHTML = messageHTML;
            chatArea.appendChild(messageDiv);
            chatArea.scrollTop = chatArea.scrollHeight;
        }

        // 设置加载状态
        function setLoading(loading) {
            isLoading = loading;
            sendBtn.disabled = loading;
            
            if (loading) {
                sendBtn.textContent = '🤔 思考中...';
                document.getElementById('loading').style.display = 'block';
            } else {
                sendBtn.textContent = '🚀 发送消息';
                document.getElementById('loading').style.display = 'none';
            }
        }

        // 获取知识库内容
        async function getKnowledgeByCategory(category) {
            try {
                const response = await fetch(`/api/knowledge/${category}`);
                const data = await response.json();
                
                if (data.success) {
                    let content = `📚 ${category} 知识库内容：\n\n`;
                    data.knowledge.forEach(item => {
                        content += `**${item.topic}**\n${item.content}\n来源：${item.source}\n\n`;
                    });
                    addMessage('assistant', content);
                }
            } catch (error) {
                console.error('获取知识库失败:', error);
            }
        }

        // 快捷功能按钮
        function showLearningTips() {
            userInput.value = '请基于智源研究院的教育理论，为我提供个性化的学习建议';
            sendMessage();
        }

        function showProductivityTips() {
            userInput.value = '请结合智源研究院的生产力研究，帮我制定高效的工作方法';
            sendMessage();
        }

        function showCreativityTips() {
            userInput.value = '请利用智源研究院的创新理论，帮我激发创造性思维';
            sendMessage();
        }

        // 添加快捷按钮到页面
        window.addEventListener('load', function() {
            const shortcuts = document.createElement('div');
            shortcuts.innerHTML = `
                <div style="text-align: center; margin: 20px 0;">
                    <button onclick="showLearningTips()" style="margin: 5px; padding: 10px 20px; background: #28a745; color: white; border: none; border-radius: 5px; cursor: pointer;">🎓 学习建议</button>
                    <button onclick="showProductivityTips()" style="margin: 5px; padding: 10px 20px; background: #007bff; color: white; border: none; border-radius: 5px; cursor: pointer;">🚀 生产力提升</button>
                    <button onclick="showCreativityTips()" style="margin: 5px; padding: 10px 20px; background: #6f42c1; color: white; border: none; border-radius: 5px; cursor: pointer;">💡 创意激发</button>
                </div>
            `;
            document.querySelector('.container').appendChild(shortcuts);
        });
    </script>
</body>
</html>